/*
* Runs.cpp
* Last edited: 21.07.2014
* Author: David Noack
*/

#include "Runs.h"

//Inittialize the base class with the input data
Runs::Runs(bool* bitArray, int bitArraySize) : NistTest(bitArray, bitArraySize)
{
	tau = 0.0;
	vn_obs = 0.0;
};


double Runs::execute(int size)
{
	n = size;
	double numerator = 0.0;
	double denominator = 0.0;

	if (testPi()) //test if the monobit test is passed
	{
		for (int i = 0; i < size-1 ; i++)
		{
			if (bitArray[i] == bitArray[i + 1])
				vn_obs += 0;
			else
				vn_obs += 1;
		}
		vn_obs += 1;

		//Compute the p_value
		numerator = std::abs(vn_obs - 2*n*pi*(1-pi));
		denominator = 2 * std::sqrt(2 * n*pi*(1 - pi));
		p_value = std::erfc(numerator/denominator);
	}
	else //Monobit-Test was not passed, so p_value becomes 0.0 i.e. Runs Test is not performed
	{
		p_value = 0.0;
	}

	return p_value;
}


bool Runs::testPi()
{
	for (int i = 0; i < n; i++)
	{
		pi += bitArray[i];
	}
	pi = pi / n;


	tau = 2.0/std::sqrt(n);

	if (fabs(pi - 0.5) < tau)
		return true;
	else
		return false;
}
